/**
 * 白名单数据库操作
 */
use diesel::prelude::*;
use crate::model::allow_list_model::*;

/// Run query using Diesel to find user by uid and return it.
pub fn find_by_id(
    allow_list_id: &str,
    conn: &SqliteConnection,
) -> Result<Option<AllowList>, super::DbError> {
    use crate::schema::allow_lists::dsl::*;

    let allow_list = allow_lists
        .filter(id.eq(allow_list_id))
        .first::<AllowList>(conn)
        .optional()?;

    Ok(allow_list)
}

pub fn find_by_page(
    page: i64,
    size: i64,
    conn: &SqliteConnection,
) -> Result<(Option<Vec<AllowList>>, i64), super::DbError> {
    use crate::schema::allow_lists::dsl::*;

    let offset = (page - 1) * size;

    let alert_vec = allow_lists
        .order(create_time.desc())
        .limit(size)
        .offset(offset)
        .load::<AllowList>(conn)
        .optional()?;

    let count = allow_lists.count().get_result::<i64>(conn)?;

    Ok((alert_vec, count))
    
}

/// Run query using Diesel to insert a new database row and return the result.
pub fn insert(
    // prevent collision with `name` column imported inside the function
    new_allow_list: AllowList,
    conn: &SqliteConnection,
) -> Result<AllowList, super::DbError> {
    // It is common when using Diesel with Actix Web to import schema-related
    // modules inside a function's scope (rather than the normal module's scope)
    // to prevent import collisions and namespace pollution.
    use crate::schema::allow_lists::dsl::*;

    diesel::insert_into(allow_lists).values(&new_allow_list).execute(conn)?;

    Ok(new_allow_list)
}




pub fn delete_by_id(
    record_id: &str,
    conn: &SqliteConnection,
) -> Result<(), super::DbError> {
    use crate::schema::allow_lists::dsl::*;
    diesel::delete(allow_lists).filter(id.eq(record_id)).execute(conn)?;
    Ok(())
}